const fs = require('fs')
const { Writable } = require('stream');


class MyWritable extends Writable {
  constructor(options) {
    super(options);
    this.fileStream = fs.createWriteStream(options.filename, { encoding: 'utf8' });
  }

  /**
   * 处理数据块
   * 
   * @param chunk 一个 Buffer 或字符串
   * @param encoding 数据的编码，如果 chunk 是 Buffer，则 encoding 为 'buffer'
   * @param callback 调用它表示数据处理完成
   * @private
   */
  _write(chunk, encoding, callback) {
    // 示例：将数据块转换为字符串并打印
    console.log(`Received ${chunk.length} bytes of data: ${chunk.toString()}`);
    console.log(`Received encoding: ${encoding}`);
    
    // 将数据块写入文件
    this.fileStream.write(chunk, encoding, (err) => {
      if (err) {
        // 如果发生错误，调用 callback 并传递错误对象
        callback(err);
      } else {
        // 数据处理完成，调用 callback
        callback();
      }
    });
  }

  _final(callback) {
    // 关闭文件流
    this.fileStream.end(callback);
  }
}

const myWritable = new MyWritable({ filename: 'example.txt' });

myWritable.on('finish', () => {
  console.log('All data has been written');
});

myWritable.on('error', (err) => {
  console.error('Error:', err);
});

// 写入数据
myWritable.write('Hello, ', 'utf8', () => {
  console.log('First chunk has been written.');
});

myWritable.write('World!', 'utf8', () => {
  console.log('Second chunk has been written.');
});

// 结束流
myWritable.end(' This is the end.', 'utf8', () => {
  console.log('Stream has ended.');
});